import { useEffect, useState } from "react";
import "./index.scss";
import OpenAI from "openai";

const deepSpeekKey = "sk-7b87ac4078b84c1e808a3ecae0e3e0eb";

const openai = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: deepSpeekKey,
  dangerouslyAllowBrowser: true,
});

interface MessageType {
  role: string;
  content: string | null;
}

interface ConvsationType {
  id: number;
  title: string;
  message: MessageType[];
}

const DeepSeek = () => {
  const [loading, setLoading] = useState(false);
  // 存储当前 文本的输入的内容
  const [value, setValue] = useState("");
  // 总数据
  const [convsationList, setConvsationList] = useState<ConvsationType[]>(
    JSON.parse(localStorage.getItem("convsationList")) || [
      {
        id: 1,
        title: "对话一",
        message: [] as MessageType[],
      },
    ]
  );

  // 选中的当前id
  const [currentID, setCurrentId] = useState(1);
  // 这个是当前id对应的数据
  const currentConvsationItem = convsationList.find((v) => v.id === currentID);
  // 是 input 键盘按下
  // const handleOnKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  //   if (e.key === "Enter") {
  //     handleEnter();
  //   }
  // };
  // 键盘 按下 回车键位 enter
  const handleEnter = async () => {
    // 非空验证
    const content = value.trim();
    if (!content) return;
    setLoading(true);

    // 清空输入框
    setValue("");
    // 查找当前最新的对话
    const item = convsationList.find((v) => v.id === currentID)!;
    // 将用户输入的内容， 立即放入列表中显示
    item.message.push({
      role: "user",
      content: content,
    });
    // 更新视图
    setConvsationList([...convsationList]);

    /*********** 第一次问问题 修改标题 *************/
    if (item.message.length === 1) {
      item.title = content;
    }
    /*********** Ai 交互 *************/
    try {
      // 开始请求 ai 大模型
      const completion = await openai.chat.completions.create({
        messages: item.message,
        model: "deepseek-chat",
        // 开启 sse 流式传输
        stream: true,
      });

      // AI返回的结果
      const AiMessage = {
        role: "assistant",
        content: "",
      };
      // 将结果推入到列表
      item.message.push(AiMessage);
      // sse 流式接受结果
      for await (const data of completion) {
        setLoading(false);
        //  每一次结果过来， 将结果添加到  AI返回的结果
        AiMessage.content += data.choices[0].delta.content;
        // 更新视图
        setConvsationList([...convsationList]);
      }
    } catch {}
  };

  // 创建对话
  const addCanveration = () => {
    const id = Date.now()
    // 添加新对话
    setConvsationList([
      { id: id, title: "新对话", message: [] },
      ...convsationList,
    ]);
    // 将高亮切换到新对话
    setCurrentId(id)
  };

  useEffect(() => {
    localStorage.setItem("convsationList", JSON.stringify(convsationList));
  }, [convsationList]);

  return (
    <div className="container">
      <div className="left">
        <div className="new-chat-btn" onClick={() => addCanveration()}>
          + 新建对话
        </div>
        <div className="conversation-list">
          {convsationList.map((v) => (
            <div
              key={v.id}
              className={`conversation-item ${
                v.id === currentID ? "active" : ""
              }`}
              onClick={() => setCurrentId(v.id)}
              title={v.title}
            >
              {v.title}
            </div>
          ))}
        </div>
      </div>
      <div className="right">
        <div className="output">
          {currentConvsationItem?.message.length === 0 ? (
            <div className="empty-state">开始新的对话吧！</div>
          ) : (
            currentConvsationItem?.message.map((message, index) => (
              <div
                key={index}
                className={`message ${
                  message.role === "user" ? "user-message" : "ai-message"
                }`}
              >
                <div className="message-content">{message.content}</div>
              </div>
            ))
          )}

          {loading && (
            <div className="message ai-message">
              <div className="message-content">
                <span className="loading">AI 正在思考...</span>
              </div>
            </div>
          )}
        </div>
        <div className="input">
          <textarea
            value={value}
            onChange={(e) => setValue(e.target.value)}
            // onKeyDown={(e) => handleOnKeyDown(e)}
            placeholder="输入消息... (Shift + Enter 换行，Enter 发送)"
          />
          <button onClick={() => handleEnter()}>发送</button>
        </div>
      </div>
    </div>
  );
};

export default DeepSeek;
